package com.goods.order.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.goods.config.AlipayConfig;
import com.goods.entity.Order;
import com.goods.entity.User;
import com.goods.order.service.OrderService;
import com.goods.povos.OrderPovo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @RequestMapping("/ReturnURL")
    public String returnURL(Model model,HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, AlipayApiException {
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

//      验证签是否合法
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if (signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            Order order = new Order();
            order.setOid(out_trade_no);
            order.setStatus(2);
            orderService.changeOrderStatus(order);
            model.addAttribute("msg","支付成功");
            model.addAttribute("code","success");


            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");


        } else {
            model.addAttribute("msg","支付失败");
            model.addAttribute("code","error");
        }
        //——请在这里编写您的程序（以上代码仅作参考）——
        return "jsps/msg";
    }

    @RequestMapping("/Pay")
    public void pay(Order order, HttpServletRequest request,HttpServletResponse response) throws AlipayApiException, IOException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
//        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = order.getOid();
        //付款金额，必填
        String total_amount = order.getTotal().toString();
        //订单名称，必填
        String subject = "订单名称:" + order.getOid();
        //商品描述，可空
        String body = "描述：" + order.getOid() + "时间:" + new SimpleDateFormat("yyyy-MM-dd :HH:mm:ss").format(new Date());

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        //输出
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print(result);
    }

    @RequestMapping("/WillPay/{oid}/{total}")
    public String willPay(Model model, @PathVariable String oid, @PathVariable BigDecimal total) {
        Order order = new Order();
        order.setOid(oid);
        order.setTotal(total);
        model.addAttribute("order", order);
        return "jsps/order/pay";
    }

    @RequestMapping("/AddOrder")
    public String addOrder(BigDecimal total, String address, String[] ids, Model model,
                           HttpSession session) {
        User user = (User) session.getAttribute("user");
        String uid = user.getUid();
        System.out.println(total + ":" + address + ":" + Arrays.asList(ids) + ":" + uid);
        Order order = orderService.addOrder(total, address, ids, uid);

        model.addAttribute("order", order);
        return "jsps/order/ordersucc";
    }


    @RequestMapping("/ChangeOrderStatus")
    public String changeOrderStatus(Order order, HttpSession session) {
        User u = (User) session.getAttribute("user");
        String uid = u.getUid();

        orderService.changeOrderStatus(order);
        return "redirect:/order/GetOrdersByUid?uid=" + uid;
    }
//    admin修改状态并返回订单列表
    @RequestMapping("/AdminChangeOrderStatus")
    public String AdminchangeOrderStatus(Order order, HttpSession session) {
        orderService.changeOrderStatus(order);
        return "redirect:/order/GetOrdersAll";
    }


    @RequestMapping("/GetOrderPovoByOid")
    public String getOrderPovoByOid(String oid, Model model) {

        OrderPovo vo = orderService.getOrderPovoByOid(oid);
        model.addAttribute("orderpovo", vo);
        return "jsps/order/desc";
    }

//    admin查看订单详情
    @RequestMapping("/AdminGetOrderPovoByOid")
    public String adminGetOrderPovoByOid(String oid, Model model) {

        OrderPovo vo = orderService.getOrderPovoByOid(oid);
        model.addAttribute("orderpovo", vo);
        return "adminjsps/admin/order/desc";
    }

//返回单个用户的订单
    @RequestMapping("/GetOrdersByUid")
    public String getOrdersByUid(String uid, Model model) {


        List<OrderPovo> order_povos = orderService.getOdersByUid(uid);

        model.addAttribute("orderpovos", order_povos);

        return "jsps/order/list";

    }

//    返回所有用户的订单
    @RequestMapping("/GetOrdersAll")
    public String getOrdersAll(Model model) {
        List<OrderPovo> order_povos = orderService.getOrdersAll();
        model.addAttribute("orderpovos", order_povos);
        return "adminjsps/admin/order/list";
    }
}
